<script setup lang="ts">
import type { ToolsBtn, TableBuilderProps } from '@/types/fcform'
import type { tableInfoState } from '@/types/hooks'
import type { FormProps } from 'naive-ui'
import NFormBuilder from '@/components/NFormBuilder/index.vue'
import { NButton, NSpace } from 'naive-ui'
import { omit } from 'lodash-es'
import { useAppsStore } from '@/stores/modules/app.ts'
import { storeToRefs } from 'pinia'
import fastUnit from '@/composables/fastUnit.ts'

const props = withDefaults(defineProps<TableBuilderProps>(), {
  searchItems: () => [], // 默认表单项为空数组
  tools: () => ({ add: false, del: false }), // 默认工具栏配置
  table: () => ({ key: 'id', columns: [] }), // 默认表格配置
})

const tableInfo = defineModel<tableInfoState<Record<string, unknown>>>({
  required: true,
})

const stores = useAppsStore()
const { permissions } = storeToRefs(stores)

/**
 * 按钮设置
 * */
const showBtn = (item: boolean | ToolsBtn | null) => {
  if (!item) return false
  if (typeof item === 'boolean') return item
  if (item.auth) return permissions.value.includes(item.auth)
  return true
}
const ToolBar = () => {
  const btnNodes = []
  if (showBtn(props.tools?.add)) {
    const addProps = typeof props.tools.add === 'boolean' ? {} : omit(props.tools.add, ['auth'])
    if (!('type' in addProps)) {
      addProps.type = 'primary'
    }
    btnNodes.push(
      h(fastUnit.FcBtn, {
        ...addProps,
        onClick: () => props.table.open(),
      }),
    )
  }
  if (showBtn(props.tools?.del)) {
    const addProps = typeof props.tools.del === 'boolean' ? {} : omit(props.tools.del, ['auth'])
    if (!('type' in addProps)) {
      addProps.type = 'error'
    }
    btnNodes.push(
      h(fastUnit.FcBtn, {
        defaultIcon: 'esayIcon-shanchu',
        ...addProps,
        onClick: () => props.table.handDel(),
      }),
    )
  }
  const $slots = useSlots()
  if ($slots.btn) {
    const slotContent = $slots.btn()
    btnNodes.push(...slotContent)
  }
  return h(
    NSpace,
    {
      align: 'center',
      size: [10, 10],
    },
    () => btnNodes,
  )
}

/**
 * table设置
 * */
const rowKey = (row) => row[props.table?.key || 'id']
const container = ref()
const { height: containerHeight } = useElementSize(container)
const tableMaxHeight = computed(() => containerHeight.value - 70)

/**
 * 搜索条件
 * */
const formConfig: FormProps = {
  inline: true,
  labelPlacement: 'left',
}
</script>

<template>
  <div class="list-page">
    <template v-if="searchItems.length > 0 && tableInfo.showSearch">
      <div class="list-page-search">
        <n-form-builder
          v-model="tableInfo.queryForm"
          :formConfig="formConfig"
          :form-items="searchItems"
        >
          <template #btns>
            <n-button type="primary" @click="table.queryData()">
              <template #icon>
                <n-icon>
                  <i class="esayIcon esayIcon-sousuo"></i>
                </n-icon>
              </template>
              <span>搜索</span>
            </n-button>
          </template>
        </n-form-builder>
      </div>
    </template>
    <div class="list-page-main">
      <div class="pb20 flex flex-between">
        <n-space>
          <tool-bar>
            <template #btn>
              <slot name="toolLeft"></slot>
            </template>
          </tool-bar>
        </n-space>
        <n-space>
          <slot name="toolRight"></slot>
          <template v-if="searchItems.length > 0">
            <n-button tertiary circle @click="tableInfo.showSearch = !tableInfo.showSearch">
              <template #icon>
                <i class="esayIcon esayIcon-sousuo"></i>
              </template>
            </n-button>
          </template>
        </n-space>
      </div>
      <slot> </slot>
      <div class="table-w" ref="container">
        <n-data-table
          v-model:checked-row-keys="tableInfo.checkedRowKeys"
          :max-height="tableMaxHeight"
          :single-line="false"
          :row-key="rowKey"
          :columns="table.columns"
          :loading="tableInfo.listLoading"
          :data="tableInfo.tableData"
          v-bind="table.props || {}"
        />
      </div>
      <template v-if="table.YPagination">
        <div class="pagination mt20">
          <component :is="table.YPagination({}, {})" />
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
